<!--
 * @Descripttion: 修改相关用户信息
 * @version: 
 * @Author: 
 * @Date: 2022-05-07 15:35:23
 * @LastEditors: weidelong
 * @LastEditTime: 2022-05-07 18:24:20
-->
<template>
    <div class="setupInfo">
        <van-nav-bar
            left-arrow
            @click-left="back"
        />
         <van-cell-group>
            <van-cell title="头像" center @click="editImg">
                <template #default>
                    <van-image
                        width="50"
                        height="50"
                        :src="userInfo.img"
                        @click.stop="preview"
                    />
                </template>
            </van-cell>
            <van-cell title="名字" :value="userInfo.name" @click="editRow('名字')" is-link />
            <van-cell title="手机号" :value="userInfo.phone" @click="editRow('手机号')" is-link />
            <van-cell title="性别" :value="userInfo.sex" @click="editRow('性别')" is-link />
        </van-cell-group>
        <van-popup
            v-model:show="show"
            closeable
            round
            close-icon="close"
            position="bottom"
            :style="{ height: '35%' }"
        >
            <van-cell-group inset>
                <van-field name="uploader">
                    <template #input>
                        <van-uploader v-model="file" />
                    </template>
                </van-field>
            </van-cell-group>
            <div class="btn">
                <van-button  round type="success" size="normal" color="#1365b7" @click="onClick" > 保存 </van-button>
            </div>
        </van-popup>
        <van-popup v-model:show="showinput" :style="{ height: '25%', width: '80%' }" round>
            <van-cell-group inset>
                <van-field
                    v-if="current === '名字'"
                    v-model="userName"
                    label="名字"
                    placeholder="好的名字更容易让人记住"
                    maxlength='10'
                />
                <van-field
                    v-if="current === '手机号'"
                    v-model="phone"
                    type="number"
                    label="手机号"
                    placeholder="手机号"
                    :rules="[{ validator: validatorPhone, message: '手机号格式错误' }]"
                />
                <van-field name="性别" label="性别" v-if="current === '性别'">
                    <template #input>
                        <van-radio-group v-model="sex" direction="horizontal">
                            <van-radio name="男">男</van-radio>
                            <van-radio name="女">女</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
            </van-cell-group>
            <div class="btn">
                <van-button  round type="success" size="normal" color="#1365b7" @click="saveRow" > 保存 </van-button>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { Toast, ImagePreview } from "vant"
import {editInfo, getInfo} from '../../request/api/mineApi'
import { uploadImg } from '../../request/api/socialApi.js'

export default {
    name: 'mine',
    components: {},
    data() {
        return {
            show: false,
            showinput: false,
            current: '',
            file: [],
            imgUrl: '',
            userInfo: {
                id: '',
                img: '',
                name: '',
                phone: '',
                sex: '',
            },
            userName: '',
            phone: '',
            sex: '',
        }
    },
    created() {
        this.getUserInfo()
    },
    methods: {
        async getUserInfo() {
            Toast.loading({
                duration: 0, // 持续展示 toast
                message: '加载中...',
                forbidClick: true,
            })
            let id = JSON.parse(sessionStorage.getItem('user')).id
            const { data } = await getInfo({id})
            if (data) {
                if (data.code === 0) {
                    this.userInfo = data.userobj
                    Toast.clear()
                }
            } else {
                Toast.clear()
                Toast.fail(res.msg)
            }
        },
        // 手机号校验
		validatorPhone(val) {
			 return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(val)
		},
        back() {
            history.back()
        },
        // 头像预览
        preview() {
            ImagePreview([this.userInfo.img])
        },
        // 编辑头像
        editImg() {
            this.show = true
        },
        // 保存头像
        onClick() {
            let files = this.file
            let formdata = new FormData()
            files.map(i => {
                formdata.append('file', i.file)
            })
            uploadImg(formdata).then(res => {
                if (res.data) {
                    this.imgUrl = res.data[0].imgPath
                }
                const obj = {
                    id: JSON.parse(sessionStorage.getItem('user')).id,
                    userImg: this.imgUrl
                }
                editInfo(obj).then(res => {
                    let { data } = res
                    if (data) {
                        if (data.code === 0) {
                            this.show = false
                            this.file = []
                            this.getUserInfo()
                        }
                    }
                })
            }).catch()
        },
        // 编辑当前行信息
        editRow(row) {
            this.current = row
            this.showinput = true
        },
        // 保存当前行信息
        async saveRow() {
            const obj = {
                id: JSON.parse(sessionStorage.getItem('user')).id,
            }
            switch(this.current) {
                case '名字': 
                    obj.userName = this.userName
                    break
                case '手机号': 
                    obj.phone = this.phone
                    this.validatorPhone()
                    break
                case '性别': 
                    obj.sex = this.sex
                    break
                default: 
                    break
            }
            for(const [key, value] of Object.entries(obj)) {
                if (key !== 'id') {
                    // 内容为空不报存
                    if (value == '') {
                        Toast({
                            message: '内容为空',
                            icon: 'fail',
                        })
                    } else if (key === 'phone') {
                        // 验证手机号
                        if (this.validatorPhone(value)) {
                            let { data } = await editInfo(obj)
                            if (data) {
                                if (data.code === 0) {
                                    sessionStorage.setItem('user', JSON.stringify(data.userObj))
                                    this.getUserInfo()
                                    this.showinput = false
                                }
                            }
                        } else {
                            Toast({message: '格式错误',icon: 'fail',})
                        }
                    } else {
                            let { data } = await editInfo(obj)
                            if (data) {
                                if (data.code === 0) {
                                    sessionStorage.setItem('user', JSON.stringify(data.userObj))
                                    this.getUserInfo()
                                    this.showinput = false
                                }
                            }
                    }
                }
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.van-popup {
    position: relative;
    .van-cell-group {
        position: absolute;
        top: 40%;
        transform: translateY(-50%);
    }
    .btn {
        position: absolute;
        bottom: 10px;
        width: 100%;
        text-align: center;
        .van-button{
            width: 80%;
        }
    }
}
</style>